// 新增学生
import Base from "../base.js";
import cinemasApi from "../../api/cinemas.js";

export default class extends Base {
    constructor(props) {
        super(props);
        this.data = {
            cinemas: {
                _id: props._id,
            },
        }
    }
    // 函数渲染
    render() {
        this.$el.html(`
        <div>
            <h1>图片上传</h1>
            <table>
                <tr>
                    <td>影院名称:</td>
                    <td class="cinemaName"></td>
                </tr>
                <tr>
                    <td></td>
                    <td>
                        <button type="button" class="layui-btn" id="upload-btn">
                            <i class="layui-icon">&#xe67c;</i>上传图片
                        </button>
                    </td>
                </tr>
                <tr>
                <td>图片列表</td>
                <td class="imgs"></td>
            </tr>
            </table>
        </div>
    `);
    //获取页面节点
    this.$cinemasEle=$('.cinemaName');
    this.$uploadEle=$('#upload-btn');
    this.$imgsEle = $(".imgs");
       
    }




    // 再次渲染让用户的数据渲染到页面
    rerender() {
        console.log('rerender');
        const {name}=this.data.cinemas;
        this.$cinemasEle.html(name);
        const imgStr = _.map(this.data.cinemas.imgs, item => {
            return `<img style="width:100px; height:100px;" src="/resource${item}" />`
        }).join("");
        this.$imgsEle.html(imgStr);
    }

    // 点击删除图片
    async delete(e) {
        const { _id } = this.data.cinemas;
        // replace 替换
        const url = $(e.target).attr("src").replace("/resource", "");
        this.data.cinemas = await cinemasApi.deleteImg({ _id, url });
        //删除图片，解除关联关系后重新渲染
        this.rerender();
    }



    // 添加事件
    handle() {
        // 引入layui
        this.upload = layui.upload;
        this.upload.render({
            elem: '#upload-btn' //绑定元素
            , url: '/resource/cinemas/upload/' //上传接口
            , data: {
                _id: () => {
                    return this.data.cinemas._id; //拿到学生的id
                }
            }
            , multiple: true  //是否允许多文件上传
            // 上传成功之后的回调函数
            , done: res => {
                //将最新的数据赋值给cinemas
                this.data.cinemas = res;
                this.rerender();
            }
            , error: function () {
                //请求异常回调
            }
        });
    //     // 点击的时候删除图片
        this.$imgsEle.on("click", "img", this.delete.bind(this));
    };



    // 获取需要上传信息的电影
    async getOne() {
        const { _id } = this.data.cinemas;
        this.data.cinemas = await cinemasApi.getOne(_id);
    }

    // 当render结束 mounted开始
    async mounted() {
        // 调用getOne
        await this.getOne();
        this.rerender();
    }

}
